from datetime import datetime
import re
from info import redis_store, constants, db
from info.lib.yuntongxun.sms import CCP
from info.models import User
from info.utitils.captcha.captcha import captcha
from info.utitils.response_code import RET
from . import passport_bp
from flask import request, current_app, abort, make_response, jsonify, session, current_app

@passport_bp.route("/login_out",methods=["POST"])
def login_out():
    session.pop("user_id")
    session.pop("mobile")
    session.pop("nick_name")

    return jsonify(errno=RET.OK,errmsg="退出登录成功")

@passport_bp.route("/login",methods=["POST"])
def login():

    # 1.获取参数
    # 1.1 mobile:手机号码， password：未加密的密码
    param_dict = request.json
    mobile = param_dict.get("mobile")
    password = param_dict.get("password")
    # 2.校验参数
    # 2.1 非空判断
    if not all([mobile, password]):
        return jsonify(error=RET.PARAMERR, errmsg="参数不足")

    # 2.2 手机号码格式判断
    if not re.match("1[3456789][0-9]{9}",mobile):
        current_app.logger.error("手机格式错误")
        return jsonify(error=RET.PARAMERR, errmsg="手机格式错误")

    # 3.逻辑处理
    # 3.1 根据手机号码去查询当前用户user
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")
    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")
    # 3.2 使用user对象判断用户填写的密码是否跟数据库里的一致
    if not user.check_passowrd(password):
        return jsonify(errno=RET.DATAERR, errmsg="密码填写错误")

    # 3.3 使用session记录用户登录信息
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    # 3.4 修改用户最后一次登录时间
    user.last_login = datetime.now()
    # 保存回数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")

    # 4.返回值
    return jsonify(errno=RET.OK, errmsg="登陆成功")

@passport_bp.route("/image_code")
def get_image_code():

    code_id = request.args.get("code_id")

    if not code_id:
        current_app.logger.error("参数不足")
        abort(404)

    image_name, real_image_code, image_data = captcha.generate_captcha()

    try:
        redis_store.setex("CODEID_%s" % code_id, constants.IMAGE_CODE_REDIS_EXPIRES, real_image_code)
    except Exception as e:
        current_app.logger.error(e)

    response = make_response(image_data)
    response.headers["Content-Type"] = "image/JPEG"
    return response

@passport_bp.route("/sms_code",methods=["POST"])
def send_sms_code():

    param_dict = request.json
    mobile = param_dict.get("mobile")
    image_code = param_dict.get("image_code")
    image_code_id = param_dict.get("image_code_id")

    if not all([mobile,image_code, image_code_id]):
        err_dict = {"errno": RET.PARAMERR, "errmsg": "参数不足"}
        return jsonify(err_dict)

    if not re.match("1[3456789][0-9]{9}",mobile):
        current_app.logger.error("电话号码格式错误")

    real_image_code = None
    try:
        real_image_code = redis_store.get("CODEID_%s" % image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error = RET.DBERR, errmsg = "获取真实的图片验证码错误")

    if not real_image_code:
        current_app.logger.error("图片验证码过期了")
        return jsonify(error=RET.NODATA,errmsg="图片验证码过期了")
    else:
        try:
            redis_store.delete("CODEID_%s" % image_code_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(error=RET.DBERR, errmsg="删除真实的图片验证码异常")
    # print(image_code, real_image_code)
    if image_code.lower() != real_image_code.lower():
        return jsonify(error=RET.DATAERR, errmsg="图片验证码填写错误")

    # TODO: 判断用户填写的手机号码是否已经注册（提高用户体验）
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg="查询用户对象异常")

    if user:
        return jsonify(error=RET.DATAEXIST,errmsg="用户已经注册过了")

    import random
    sms_code = random.randint(0,9999999)
    sms_code = "%06d" % sms_code

    result = CCP().send_template_sms(mobile,{sms_code,constants.SMS_CODE_REDIS_EXPIRES/60},1)

    if result == -1:
        return jsonify(error=RET.THIRDERR,errmsg="云通讯发短信验证码失败")
    elif result ==0:
        redis_store.setex("SMS_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES,sms_code)

    return jsonify(error=RET.OK, errmsg="发送短信验证码成功")

@passport_bp.route("/register",methods=["POST"])
def register():
    # 1.1 mobile:手机号码 ，sms_code:用户填写的短信验证码，password:未加密的密码
    param_dict = request.json
    mobile = param_dict.get("mobile")
    sms_code = param_dict.get("sms_code")
    password = param_dict.get("password")

    # 2.1 非空判断
    if not all([mobile, sms_code, password]):
        current_app.logger.error("参数不足")
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    # 2.2 手机号码格式正则校验
    if not re.match("1[3456789][0-9]{9}",mobile):
        current_app.logger.error("手机格式错误")
        return jsonify(error=RET.PARAMERR,errmsg="手机格式错误")
    # 3.1 根据手机号码获取redis中的真实的短信验证码值real_sms_code
    try:
        real_sms_code = redis_store.get("SMS_%s" % mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, errmsg="查询用户对象异常")
    # 3.1.1 real_sms_code有值： 从redis数据库中删除
    if real_sms_code:
        redis_store.delete("SMS_%s" % mobile)
    # 3.1.2 real_sms_code没有值：短信验证码过期了
    else:
        current_app.logger.error("短信验证码过期")
        return jsonify(error=RET.NODATA,errmsg="短信验证码过期")
    # 3.2 对比用户填写的短信验证码值和真实的短信验证码值是否一致
    if sms_code != real_sms_code:
        return jsonify(errno=RET.DATAERR,errmsg="短信验证码错误")
    # 3.2.2 相等：注册
    # 3.3 创建用户对象，并给各个属性赋值
    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    # 当前时间最为最后一次登录时间
    user.last_login = datetime.now()
    user.password = password
    # 3.4 将用户存储到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(error=RET.DBERR, errmsg="添加用户对象到数据库异常")
    # 3.5 注册成功代表登录成功，记录用户登录信息到sesssion中
    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name

    # 4.注册成功
    return jsonify(error=RET.OK, errmsg="注册成功")




















































